<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF转图片工具</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-6 py-8">
        <div class="max-w-4xl mx-auto">
            <!-- 标题 -->
            <div class="text-center mb-8">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">
                    <i class="fas fa-file-pdf text-red-500 mr-2"></i>
                    PDF转图片工具
                </h1>
                <p class="text-gray-600">将PDF文档转换为高质量的JPG、PNG图片格式</p>
            </div>
            
            <!-- 上传区域 -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
                <div id="uploadArea" class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer">
                    <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-700 mb-2">选择或拖拽PDF文件</h3>
                    <p class="text-gray-500 mb-4">支持PDF格式，最大文件大小10MB</p>
                    <input type="file" id="pdfInput" accept=".pdf" class="hidden">
                    <button onclick="document.getElementById('pdfInput').click()" 
                            class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                        选择文件
                    </button>
                </div>
            </div>
            
            <!-- 转换选项 -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6" id="optionsPanel" style="display: none;">
                <h3 class="text-lg font-semibold mb-4">转换选项</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">输出格式</label>
                        <select id="outputFormat" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                            <option value="png">PNG</option>
                            <option value="jpeg">JPEG</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">图片质量</label>
                        <select id="quality" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                            <option value="1">标准 (1x)</option>
                            <option value="1.5">高质量 (1.5x)</option>
                            <option value="2">超高质量 (2x)</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">页面范围</label>
                        <select id="pageRange" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                            <option value="all">所有页面</option>
                            <option value="first">仅第一页</option>
                            <option value="custom">自定义范围</option>
                        </select>
                    </div>
                </div>
                <div id="customRange" class="mt-4" style="display: none;">
                    <label class="block text-sm font-medium text-gray-700 mb-2">页面范围 (例如: 1-3, 5, 7-9)</label>
                    <input type="text" id="customPages" placeholder="1-3, 5, 7-9" 
                           class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>
                <div class="mt-6">
                    <button onclick="convertPDF()" 
                            class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition-colors">
                        <i class="fas fa-magic mr-2"></i>
                        开始转换
                    </button>
                </div>
            </div>
            
            <!-- 进度条 -->
            <div id="progressPanel" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6" style="display: none;">
                <h3 class="text-lg font-semibold mb-4">转换进度</h3>
                <div class="w-full bg-gray-200 rounded-full h-2 mb-4">
                    <div id="progressBar" class="bg-blue-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
                </div>
                <p id="progressText" class="text-sm text-gray-600">准备转换...</p>
            </div>
            
            <!-- 结果展示 -->
            <div id="resultPanel" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6" style="display: none;">
                <h3 class="text-lg font-semibold mb-4">转换结果</h3>
                <div id="imageGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <!-- 动态生成的图片将在这里显示 -->
                </div>
                <div class="mt-6 text-center">
                    <button onclick="downloadAll()" 
                            class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors mr-4">
                        <i class="fas fa-download mr-2"></i>
                        下载所有图片
                    </button>
                    <button onclick="resetTool()" 
                            class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700 transition-colors">
                        <i class="fas fa-redo mr-2"></i>
                        重新转换
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let pdfDoc = null;
        let convertedImages = [];
        
        // 设置PDF.js worker
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
        
        // 文件上传处理
        document.getElementById('pdfInput').addEventListener('change', handleFileSelect);
        
        // 拖拽上传
        const uploadArea = document.getElementById('uploadArea');
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('border-blue-500', 'bg-blue-50');
        });
        
        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('border-blue-500', 'bg-blue-50');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('border-blue-500', 'bg-blue-50');
            const files = e.dataTransfer.files;
            if (files.length > 0 && files[0].type === 'application/pdf') {
                document.getElementById('pdfInput').files = files;
                handleFileSelect({ target: { files: files } });
            }
        });
        
        // 页面范围选择
        document.getElementById('pageRange').addEventListener('change', function() {
            const customRange = document.getElementById('customRange');
            if (this.value === 'custom') {
                customRange.style.display = 'block';
            } else {
                customRange.style.display = 'none';
            }
        });
        
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file && file.type === 'application/pdf') {
                const reader = new FileReader();
                reader.onload = function(e) {
                    loadPDF(e.target.result);
                };
                reader.readAsArrayBuffer(file);
            } else {
                alert('请选择有效的PDF文件');
            }
        }
        
        async function loadPDF(arrayBuffer) {
            try {
                pdfDoc = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
                document.getElementById('optionsPanel').style.display = 'block';
                
                // 更新上传区域显示
                const uploadArea = document.getElementById('uploadArea');
                uploadArea.innerHTML = `
                    <i class="fas fa-file-pdf text-4xl text-red-500 mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-700 mb-2">PDF已加载</h3>
                    <p class="text-gray-500">共 ${pdfDoc.numPages} 页</p>
                `;
                uploadArea.classList.remove('cursor-pointer');
            } catch (error) {
                console.error('PDF加载失败:', error);
                alert('PDF文件加载失败，请检查文件是否损坏');
            }
        }
        
        async function convertPDF() {
            if (!pdfDoc) {
                alert('请先选择PDF文件');
                return;
            }
            
            const format = document.getElementById('outputFormat').value;
            const quality = parseFloat(document.getElementById('quality').value);
            const pageRange = document.getElementById('pageRange').value;
            
            let pagesToConvert = [];
            
            if (pageRange === 'all') {
                for (let i = 1; i <= pdfDoc.numPages; i++) {
                    pagesToConvert.push(i);
                }
            } else if (pageRange === 'first') {
                pagesToConvert = [1];
            } else if (pageRange === 'custom') {
                const customPages = document.getElementById('customPages').value;
                pagesToConvert = parsePageRange(customPages, pdfDoc.numPages);
            }
            
            if (pagesToConvert.length === 0) {
                alert('请指定有效的页面范围');
                return;
            }
            
            // 显示进度面板
            document.getElementById('progressPanel').style.display = 'block';
            document.getElementById('resultPanel').style.display = 'none';
            convertedImages = [];
            
            for (let i = 0; i < pagesToConvert.length; i++) {
                const pageNum = pagesToConvert[i];
                const progress = ((i + 1) / pagesToConvert.length) * 100;
                
                document.getElementById('progressBar').style.width = progress + '%';
                document.getElementById('progressText').textContent = `正在转换第 ${pageNum} 页... (${i + 1}/${pagesToConvert.length})`;
                
                try {
                    const imageData = await convertPage(pageNum, quality, format);
                    convertedImages.push({
                        pageNum: pageNum,
                        data: imageData,
                        format: format
                    });
                } catch (error) {
                    console.error(`第 ${pageNum} 页转换失败:`, error);
                }
                
                // 添加小延迟以显示进度
                await new Promise(resolve => setTimeout(resolve, 100));
            }
            
            // 显示结果
            displayResults();
        }
        
        async function convertPage(pageNum, quality, format) {
            const page = await pdfDoc.getPage(pageNum);
            const viewport = page.getViewport({ scale: quality });
            
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            
            await page.render({ canvasContext: context, viewport: viewport }).promise;
            
            return canvas.toDataURL(`image/${format}`, format === 'jpeg' ? 0.9 : undefined);
        }
        
        function parsePageRange(rangeStr, maxPages) {
            const pages = [];
            const parts = rangeStr.split(',');
            
            for (const part of parts) {
                const trimmed = part.trim();
                if (trimmed.includes('-')) {
                    const [start, end] = trimmed.split('-').map(n => parseInt(n.trim()));
                    for (let i = start; i <= Math.min(end, maxPages); i++) {
                        if (i >= 1 && !pages.includes(i)) {
                            pages.push(i);
                        }
                    }
                } else {
                    const pageNum = parseInt(trimmed);
                    if (pageNum >= 1 && pageNum <= maxPages && !pages.includes(pageNum)) {
                        pages.push(pageNum);
                    }
                }
            }
            
            return pages.sort((a, b) => a - b);
        }
        
        function displayResults() {
            document.getElementById('progressPanel').style.display = 'none';
            document.getElementById('resultPanel').style.display = 'block';
            
            const imageGrid = document.getElementById('imageGrid');
            imageGrid.innerHTML = '';
            
            convertedImages.forEach((image, index) => {
                const imageCard = document.createElement('div');
                imageCard.className = 'border border-gray-200 rounded-lg p-4';
                imageCard.innerHTML = `
                    <img src="${image.data}" alt="第 ${image.pageNum} 页" class="w-full h-48 object-contain border border-gray-200 rounded mb-3">
                    <div class="text-center">
                        <p class="text-sm text-gray-600 mb-2">第 ${image.pageNum} 页</p>
                        <button onclick="downloadImage(${index})" 
                                class="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700 transition-colors">
                            <i class="fas fa-download mr-1"></i>
                            下载
                        </button>
                    </div>
                `;
                imageGrid.appendChild(imageCard);
            });
        }
        
        function downloadImage(index) {
            const image = convertedImages[index];
            const link = document.createElement('a');
            link.download = `page_${image.pageNum}.${image.format}`;
            link.href = image.data;
            link.click();
        }
        
        function downloadAll() {
            convertedImages.forEach((image, index) => {
                setTimeout(() => {
                    downloadImage(index);
                }, index * 500); // 延迟下载避免浏览器阻止
            });
        }
        
        function resetTool() {
            pdfDoc = null;
            convertedImages = [];
            document.getElementById('pdfInput').value = '';
            document.getElementById('optionsPanel').style.display = 'none';
            document.getElementById('progressPanel').style.display = 'none';
            document.getElementById('resultPanel').style.display = 'none';
            
            // 重置上传区域
            const uploadArea = document.getElementById('uploadArea');
            uploadArea.innerHTML = `
                <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                <h3 class="text-lg font-medium text-gray-700 mb-2">选择或拖拽PDF文件</h3>
                <p class="text-gray-500 mb-4">支持PDF格式，最大文件大小10MB</p>
                <button onclick="document.getElementById('pdfInput').click()" 
                        class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                    选择文件
                </button>
            `;
            uploadArea.classList.add('cursor-pointer');
        }
    </script>
</body>
</html>